package com.zpark.dao.impl;

import com.zpark.dao.ScoreDao;
import com.zpark.entity.Course;
import com.zpark.entity.Score;
import com.zpark.utils.DaoUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ScoreDaoImpl implements ScoreDao {
    @Override
    public void insert(Integer studentId, Integer courseId) {
        String sql = "insert into score(student_id,course_id) values (?,?)";
        try {
            DaoUtil.executeUpdate(sql,studentId,courseId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateStatus(Integer studentId, Integer courseId, Integer status) {
        String sql = "update score set status=? where student_id=? and course_id = ? ";
        try {
            DaoUtil.executeUpdate(sql,status,studentId,courseId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateScore(Score score) {
        int i = 0;
        String sql = "update score set score=? where student_id=? and course_id = ? ";
        try {
             i = DaoUtil.executeUpdate(sql, score.getScore(), score.getStudentId(), score.getCourseId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return i;
    }

    @Override
    public List<Score> selectScoreByCourseId(Integer courseId) {
        String sql = "select * from score where course_id = ?";
        List<Score> scores = new ArrayList<>();
        try {
            ResultSet rs = DaoUtil.executeQuery(sql, courseId);
            while (rs.next()) {
                scores.add(mapResultSetToScore(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return scores;
    }

    @Override
    public List<Score> selectScoreByStudentId(Integer studentId) {
        String sql = "select * from score where student_id = ?";
        List<Score> scores = new ArrayList<>();
        try {
            ResultSet rs = DaoUtil.executeQuery(sql, studentId);
            while (rs.next()) {
                scores.add(mapResultSetToScore(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return scores;
    }

    private Score mapResultSetToScore(ResultSet rs) throws SQLException {
        Score score = new Score();
        score.setStudentId(rs.getInt("student_id"));
        score.setCourseId(rs.getInt("course_id"));
        score.setScore(rs.getInt("score"));
        score.setStatus(rs.getInt("status"));
        return score;
    }
}
